package com.foxconn.ipebg.common.system.controller;


import ipebg.mzk.common.util.PropertyPhase;
import ipebg.mzk.common.util.StringUtils;
import ipebg.mzk.common.util.VerifyCode;
import ipebg.mzk.facade.entity.LogMongo;
import ipebg.mzk.facade.entity.MsAdminUser;
import ipebg.mzk.facade.enums.LogLevel;
import ipebg.mzk.facade.system.service.LogService;
import ipebg.mzk.facade.system.service.LoginService;
import ipebg.mzk.facade.system.service.MsAccessCountRecordService;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.foxconn.ipebg.common.base.security.SecurityUserHolder;

@Controller
@RequestMapping("/login.do")
@SessionAttributes("PortalRoot")
public class LoginController {
	private static final Log log = LogFactory.getLog(LoginController.class);

	@Resource(name = "msAccessCountRecordServiceImpl")
	MsAccessCountRecordService msAccessCountRecordServiceImpl;

	@Resource(name = "loginServiceImpl")
	private LoginService loginService;

	@Resource(name = "logServiceImpl")
	private LogService logServiceImpl;

	@Resource(name="securityUserHolder")
	SecurityUserHolder securityUserHolder;
	
	
	private String loginFlag;

	@RequestMapping(params = "action=checkName")
	public void checkName(HttpServletRequest request, HttpServletResponse response) throws Exception {

		response.setContentType("text/xml");
		response.setCharacterEncoding("UTF-8");
		StringBuffer xmlDoc = new StringBuffer();
		xmlDoc.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		xmlDoc.append("<code>");
		try {
			if (loginService.getUserByUserName(request.getParameter("inputName")) != null) {
				xmlDoc.append("<stat>ok</stat>");
			} else {
				xmlDoc.append("<stat>error</stat>");
			}

			xmlDoc.append("</code>");
			String rtnXml = xmlDoc.toString();

			response.getWriter().write(rtnXml);
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		}
	}

	@RequestMapping(params = "action=changeCode")
	public void changeCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 设置浏览器不缓存本页
		response.setHeader("Cache-Control", "no-cache");

		// 生成验证码.写入用户session
		String verifyCode = VerifyCode.generateTextCode(VerifyCode.TYPE_NUM_ONLY, 4, null);
		HttpSession session = request.getSession();
		session.setAttribute("verifyCode", verifyCode);

		// 输出验证码给客户端
		response.setContentType("image/jpeg");
		BufferedImage bim = VerifyCode.generateImageCode(verifyCode, 100, 23, 3, false, Color.WHITE, Color.BLUE, null);
		ImageIO.write(bim, "JPEG", response.getOutputStream());
	}

	@RequestMapping(params = "action=checkVerifyCode")
	public void checkVerifyCode(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		String sessionCode = (String) session.getAttribute("verifyCode");
		response.setContentType("text/xml");
		response.setCharacterEncoding("UTF-8");
		StringBuffer xmlDoc = new StringBuffer();
		xmlDoc.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		xmlDoc.append("<code>");
		try {
			if (sessionCode!=null&&sessionCode.equals(request.getParameter("inputCode"))) {
				xmlDoc.append("<stat>ok</stat>");
			} else {
				xmlDoc.append("<stat>error</stat>");
			}

			xmlDoc.append("</code>");
			String rtnXml = xmlDoc.toString();

			response.getWriter().write(rtnXml);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(params = "action=success")
	public String success(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		List<Object> objs = securityUserHolder.getLoginUsers();
		Iterator it1 =objs.iterator();
		while(it1.hasNext()){
			MsAdminUser user = (MsAdminUser) it1.next();
			System.out.print("Login user :"+user.getRealName());
		}
		
		MsAdminUser adminuser = SecurityUserHolder.getCurrentUser();
		if (adminuser != null) {
			String key = PropertyPhase.readData("REDIS_PREFIX") + "_USER_LOGIN_COUNT_" + StringUtils.GetCurrentSystemDate("yyyy_MM_dd");

			try {
				msAccessCountRecordServiceImpl.AddOnlineUser(adminuser.getLoginName());
				Long lOnline = msAccessCountRecordServiceImpl.OnlineLoginUserCount();
				System.out.println("current user count:" + lOnline);

				Set<String> setOnlineUsers = msAccessCountRecordServiceImpl.GetOnlineUserList();
				
				System.out.println("online Usser:"+setOnlineUsers.size());
				/*if (setOnlineUsers != null && setOnlineUsers.size() > 0) {
					Iterator it = setOnlineUsers.iterator();
					while (it.hasNext()) {
						System.out.println(it.next().toString());
					}
				}*/

			} catch (Exception e) {
				log.error(e.getMessage());
			}

			if (adminuser == null || adminuser.equals(null)) {
				log.info(adminuser.getLoginName() + ",登錄失敗！");
				return "/pages/common/system/login";
			} else {
				modelMap.put("PortalRoot", PropertyPhase.readData("PortalRoot"));
				request.getSession().setAttribute("userId", adminuser.getAdminId());
				request.getSession().setAttribute("username", adminuser.getLoginName());
				request.getSession().setAttribute("realname", adminuser.getRealName());
				log.info(adminuser.getLoginName() + ",登錄成功！");
				try {
					logServiceImpl.save(new LogMongo(LogLevel.INFO, adminuser.getLoginName() + ",登錄成功！"));
				} catch (Exception e) {
					e.printStackTrace();
				}
				return "/pages/common/system/index";
			}
		} else {
			log.info("ctx.getAuthentication()為空，導致登錄失敗！");
			return "/pages/common/system/login";
		}
	}

	@RequestMapping(params = "action=logout")
	public String logout(HttpServletRequest request, HttpServletResponse response) {
		HttpSession session = request.getSession();
		session.setAttribute("username", null);
		return "login.jsp";
	}

	public void setLoginFlag(String loginFlag) {
		this.loginFlag = loginFlag;
	}

	public String getLoginFlag() {
		return loginFlag;
	}

}
